$(function () {
	
    $("#grid_id").jqGrid({
    	url: "/MavenExample/mangebooks",
        datatype: "json",
        mtype: "POST",
        colNames: ["book id", "book author", "book name", "numpages", "price", "category", "images"],
        colModel:[
                  {
                      name:"bookId",
                      width:55,
                      key : true,
                      editable: true, 
                      hidden: true,
                      // TODO
                  },
                  {
                      name:"bookAuthor",
                      width:150,
                      editable: true,
                      editoptions: {
	                      maxlength: 15,
	                      dataEvents :[{
	                			type:'blur',
	                			fn: function(e){
	                				var newCodeValue = $(e.target).val();
	                				// lookup data to fill other input
	                				$('#tr_bookName .DataTD #bookName').val(newCodeValue);
	                				// hide submit button
	                				if(newCodeValue === 'hieu'){
	                					$('#Act_Buttons>.EditButton>#sData').hide();
	                				}else{
	                					$('#Act_Buttons>.EditButton>#sData').show();
	                				}
	                			},
	                		}]
                  	  },
                      editrules:{ required:true}
					  /*editable
					    edittype
					    editoptions
					    editrules
					    formoptions (valid only in form editing)*/

                  },
                  {
                      name:"bookName",
                      width:150,
                      align:"center",
                      editable: true,
                      editrules:{required:true}
                      // TODO
                  },
                  {
                      name:"numpages",
                      width:60,
                      align:"right",
                      editable: true
                      // TODO
                  },
                  {
                      name:"price",
                      width:55,
                      sortable:false,
                      editable: true
                      // TODO
                  },
                  {
                      name:"category",
                      width:150,
                      align:"center",
                      editable: true
                      // TODO
                  },
               // TODO get images
                 {
				    name: 'images',
				    index: 'images',
				    align: 'left',
				    editable: true,
				    width: 210,
				    align: 'center',
				    //formatter:imageFormat,
				    search: false
				}
              ],
        pager: "#pager",
//        rowNum: 10,
//        rowList: [10, 20, 30],
        sortname: "bookName",
        sortorder: "desc",
        viewrecords: true,
        gridview: true,
        autoencode: true,
        caption: "My first grid",
        //editurl: 'clientArray',
	    onSelectRow: function(id) {
	    	   console.log('function handler event click on row');
	    },
	    afterInsertRow: function(rowid, rowdata, rowelem){
	    	console.log('afterInsertRow');
	    },
	    beforeSelectRow: function(rowid, e){
	    	console.log('beforeSelectRow');
	    },
	    gridComplete: function(){
	    	console.log('gridComplete');
	    },
        jsonReader : {
//            root: "rows",
//            page: "page",
//            total: "total",
//            records: "records",
//            repeatitems: false,
            cell: "cell",
            id: "bookId"
        }
           
    });
    
    // for purpose convert to json object
    var rowchanesInGrid = [];
    // Setup buttons
    $("#grid_id").navGrid('#pager',{edit:true,add:true,del:true,search:false},
      // edit
	{
    	// if url = null what happen?
		//url: '/MavenExample/editBookJqgrid',\
    	url: 'clientArray',
		onclickSubmit: function(){console.log('onclickSubmit')},
		closeAfterEdit: true,
		reloadAfterSubmit:true,
		afterComplete:function (response, postdata, formid) {
			rowchanesInGrid.push($("#grid_id").getRowData(postdata.bookId));
		} 
	},
	// add
	{
		//url: '/MavenExample/editBookJqgrid',
		url : 'clientArray',
		closeAfterAdd: true,
		reloadAfterSubmit:true,
//		beforeSubmit: function(postdata, formid){
//			postdata.something = 'somevalue';
//			console.log('beforeSubmit');
//			console.log(postdata);
//			console.log(formid[0].id);
//		},
		afterComplete:function (response, postdata, formid) {
			rowchanesInGrid.push($("#grid_id").getRowData(postdata.bookId));
		} 
	},
	// del
	{
		url: '/MavenExample/deleteBookJqgrid',
		//url: 'clientArray',
		closeAfterDelete:true,
		reloadAfterSubmit:true
		// TODO
	},
	// search
	{}

); 
/*
 $("#grid_id").navGrid('#pager').jqGrid('editGridRow', rowid, {
	 closeAfterEdit: true,
	addCaption: "Add Record",
	editCaption: "Edit Record",
	bSubmit: "Submit",
	bCancel: "Cancel",
	bClose: "Close",
	saveData: "Data has been changed! Save changes?",
	bYes : "Yes",
	bNo : "No",
	bExit : "Cancel",
});*/

    
// save click function
$('#save').on('click', function(evt){
	// note that:
	 $.ajax({
		 url: "/MavenExample/editBooksJqgrid", 
		 data : JSON.stringify(rowchanesInGrid),
		 contentType:"application/json; charset=utf-8",
	    dataType:"json",
	    type: 'POST',
		 success: function(result){
		 	console.log(result.success);
		 	//reset arry rowchanesInGrid
		 	rowchanesInGrid.length = 0;
		 	// reload page
		 	location.reload(); 
	 }});
})



/*===========other function==========================*/
});